package cn.doitedu.datayi.flume;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang.StringUtils;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ApplogEncrIntercetpor implements Interceptor {
    // 需要加密的字段，如：  "account,phone"
    String encr_fields;
    // 日志中的时间戳字段名
    String ts_field;
    ApplogEncrIntercetpor(String encr_fields,String ts_field){
        this.encr_fields = encr_fields;
        this.ts_field = ts_field;
    }

    /**
     * 初始化
     */
    @Override
    public void initialize() {

    }

    /**
     * 拦截处理逻辑
     * @param event
     * @return
     */
    @Override
    public Event intercept(Event event) {
        byte[] bodyBytes = event.getBody();
        String logJson = new String(bodyBytes);
        // 解析日志json
        JSONObject jsonObject = JSON.parseObject(logJson);

        // 提取时间戳,并放入event的header中
        Long timeStamp = jsonObject.getLong(ts_field);
        event.getHeaders().put("timestamp",timeStamp+"");

        // 加密配置文件中指定的需要加密的字段
        String[] toEncrFields = encr_fields.split(",");

        // 对配置文件所指定的各个需要加密的字段，逐一加密
        for (String toEncrField : toEncrFields) {
            // 从json中取出待加密的字段的值
            String value = jsonObject.getString(toEncrField);
            if(StringUtils.isNotBlank(value)) {
                // 加密
                String cryptedValue = Md5Crypt.md5Crypt(value.getBytes());
                // 将加密后的密文，放回json
                jsonObject.put(toEncrField, cryptedValue);
            }
        }

        // 将修改后的jsonObject变回json串，放回event的body
        event.setBody(jsonObject.toJSONString().getBytes());

        return event;
    }

    /**
     * 批次拦截处理逻辑
     * @param list
     * @return
     */
    @Override
    public List<Event> intercept(List<Event> list) {
        for (Event event : list) {
            intercept(event);
        }

        return list;
    }

    /**
     * 资源清理
     */
    @Override
    public void close() {

    }

    public static class ApplogEncrIntercetporBuilder implements Interceptor.Builder{
        String encr_fields;
        String ts_field;

        /**
         * agent就是利用该build方法来获取到咱们的拦截器类的实例对象
         * @return
         */
        @Override
        public Interceptor build() {

            return new ApplogEncrIntercetpor(encr_fields,ts_field);
        }

        /**
         * agent提供给咱们用来获取agent配置文件中的参数用的方法
         * a1.sources.s1.interceptors.i1.encr_fields=account
         * a1.sources.s1.interceptors.i1.ts_field=timeStamp
         * @param context
         */
        @Override
        public void configure(Context context) {
            encr_fields = context.getString("encr_fields");
            ts_field = context.getString("ts_field");

        }
    }


}
